#include <cserver/restapi.h>
#include <boost/log/trivial.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>

#include <sstream>

namespace csrv{ namespace webcmd{
	static const char* K_this_command= "api/v1/common/userinfo";

	void user_info(Request& req, pqxx::connection&, SessionContext& sctx, const std::string& /*cmd*/ ){
		auto query = parseQuery(req.getParam("QUERY_STRING"));
		auto& callback = query["callback"];
		auto& account = query["account"];
		StreamGroup sg(req);
		auto& fout = sg.fout;

		auto sessionid = req.getCookie("sessionid");
		UserInfo user;
		{
			std::lock_guard<std::mutex> guard(sctx.mutex);
			auto pos = sctx.activeSessions.find(sessionid);
			// assert( pos != master.sessions.activeSessions.end());
			auto& uinfo = sctx.user_info.find(pos->second)->second;
			if (uinfo.role != "admin" && (!account.empty() && account != pos->second)){
				response_error(sg.fout, 403, "ErrPermission", "PermissionDenied", req);
				return;
			}
			if (account.empty())
				account = pos->second;
			auto itr = sctx.user_info.find(account);
			if (itr == sctx.user_info.end()){
				response_error(sg.fout, 400, "ErrParameter", "AccountNotFound", req);
				return;
			}
			user = itr->second;
		}

		response_header(sg.fout, 200);
		if (!callback.empty()) sg.fout << callback << "(";

#if 1
		fout << boost::format(R"({"func":"common/userinfo",
"args":{},
"ret":{"success":true, "message":"",
"value":[)");
#endif
		fout << "[";
			 fout << "{";

		fout << "\"id\":";
		fout << escape_string(user.userid);
		fout << ",";
		fout << "\"account\":";
		fout << escape_string(account);
		fout << ",";
		fout << "\"role\":";
		fout << escape_string(user.role);
		fout << ",";
		fout << "\"name\":";
		fout << escape_string(user.displayName);

		fout << "}";

		fout << "]";
		fout << "]}}";
		if (!callback.empty()) sg.fout << ")";
	}
	}

	static CommandAddHelper k_registerHandler("GET", webcmd::K_this_command, &webcmd::user_info, {"admin", "user"});
	}



